import { createStore } from 'vuex'
import api from '../services/api'

export default createStore({
  state: {
    employees: [],
    trainings: [],
    performances: [],
    positions: [],
    currentEmployee: null,
    assessmentResult: null
  },
  mutations: {
    SET_EMPLOYEES(state, employees) {
      state.employees = employees
    },
    SET_TRAININGS(state, trainings) {
      state.trainings = trainings
    },
    SET_PERFORMANCES(state, performances) {
      state.performances = performances
    },
    SET_POSITIONS(state, positions) {
      state.positions = positions
    },
    SET_CURRENT_EMPLOYEE(state, employee) {
      state.currentEmployee = employee
    },
    SET_ASSESSMENT_RESULT(state, result) {
      state.assessmentResult = result
    },
    ADD_EMPLOYEE(state, employee) {
      state.employees.push(employee)
    },
    UPDATE_EMPLOYEE(state, updatedEmployee) {
      const index = state.employees.findIndex(e => e.id === updatedEmployee.id)
      if (index !== -1) {
        state.employees.splice(index, 1, updatedEmployee)
      }
    },
    DELETE_EMPLOYEE(state, employeeId) {
      state.employees = state.employees.filter(e => e.id !== employeeId)
    }
  },
  actions: {
    async loadEmployees({ commit }) {
      try {
        const response = await api.getEmployees()
        commit('SET_EMPLOYEES', response.data)
      } catch (error) {
        console.error('加载员工数据失败:', error)
      }
    },
    async loadTrainings({ commit }) {
      try {
        const response = await api.getTrainings()
        commit('SET_TRAININGS', response.data)
      } catch (error) {
        console.error('加载培训数据失败:', error)
      }
    },
    async loadPerformances({ commit }) {
      try {
        const response = await api.getPerformances()
        commit('SET_PERFORMANCES', response.data)
      } catch (error) {
        console.error('加载绩效数据失败:', error)
      }
    },
    async loadPositions({ commit }) {
      try {
        const response = await api.getPositions()
        commit('SET_POSITIONS', response.data)
      } catch (error) {
        console.error('加载岗位数据失败:', error)
      }
    }
  },
  getters: {
    getEmployeeById: (state) => (id) => {
      return state.employees.find(employee => employee.id === id)
    },
    getTrainingsByEmployeeId: (state) => (employeeId) => {
      return state.trainings.filter(training => training.employee.id === employeeId)
    },
    getPerformancesByEmployeeId: (state) => (employeeId) => {
      return state.performances.filter(performance => performance.employee.id === employeeId)
    }
  }
})